let xAxisUniversal = {
    type: 'category',
    axisTick: {
        show: false
    },
    axisLine: {
        lineStyle: {
            color: "#9EA2A9"
        }
    },
    axisLabel: {
        color: "#DFEEF3",
        fontFamily: "SourceHanSansCNRegular",
    }
},
    yAxisUniversal = {
        type: 'value',
        splitNumber: 4,
        axisTick: {
            show: false
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            color: "#DFEEF3",
            fontFamily: "SourceHanSansCNRegular",
        },
        splitLine: {
            lineStyle: {
                color: "rgba(255,255,255,0.1)",
                type: "dashed"
            }
        }
    },
    tooltipUniversal = function (unit) {
        return {
            trigger: "axis",
            backgroundColor: "rgba(0, 43, 48, 0.8)",
            borderColor: "rgba(0, 0, 0, 0.1)",
            textStyle: {
                color: "#fff",
                fontFamily: "SourceHanSansCNRegular",
            },
            formatter: function (params) {
                let html = `<span class="tooltip-name">${params[0].name}</span><br>`
                params.forEach(item => {
                    if (item.seriesName != "背景") {
                        html += `<span class="tooltip-value">${item.seriesName}：<span>${item.value}</span>${unit}</span><br>`
                    }
                })
                return html
            }
        }
    }

/**
 * 种质资源统计
 */
function zzzytjChartInit(seriesData) {
    let myChart = echarts.init(document.getElementById("germplasm-resource-chart"));
    let option = {
        tooltip: {
            trigger: 'item',
            show: false
        },
        legend: {
            type: "scroll",
            icon: "rect",
            top: 'center',
            left: '52%',
            orient: "vertical",
            itemGap: 13,
            itemWidth: 12,
            itemHeight: 12,
            textStyle: {
                color: "#fff",
                lineHeight: 15,
                fontFamily: "SourceHanSansCNRegular",
                padding: [5, 0, 0, 5]
            },
            formatter: function (name) {
                let obj = seriesData.find(item => item.name === name);
                return name.split(" ")[0] + `\t\t\t\t\t\t\t${obj.value}个`
            },
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['45%', '65%'],
                center: ["25%", "50%"],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 13,
                        fontWeight: 'bold',
                        fontFamily: "SourceHanSansCNRegular",
                        color: '#fff',
                        formatter: function (params) {
                            let html = `{a|${params.percent}%}\n{b|${params.name}}`
                            return html
                        },
                        rich: {
                            a: {
                                color: "#F3FA3D",
                                lineHeight: 30,
                                fontSize: 18,
                                fontFamily: "SourceHanSansCNRegular",
                            },
                            b: {
                                lineHeight: 20,
                            }
                        }
                    }
                },
                labelLine: {
                    show: false
                },
                data: seriesData
            },
            {
                type: "custom",
                coordinateSystem: "none",
                renderItem: (params, api) => {
                    let imageRatio = 0.8;
                    let ratio = imageRatio > 1 ? imageRatio / 100 : imageRatio;
                    const cw = api.getWidth(), ch = api.getHeight();
                    const width = ratio * Math.min(cw, ch);
                    const abscissa = 25 / 100;
                    const ordinate = 50 / 100;
                    const deg = Math.PI * 2;
                    return {
                        type: "image",
                        style: {
                            image: './img/chart-bac.png',
                            x: cw * abscissa - width / 2,
                            y: ch * ordinate - width / 2,
                            width,
                            height: width,
                        },
                        silent: true,
                        keyframeAnimation: {
                            duration: 10000,
                            loop: true,
                            keyframes: [{
                                percent: 0,
                                rotation: 0,
                                originX: cw * abscissa,
                                originY: ch * ordinate,
                            }, {
                                percent: 1,
                                rotation: -deg,
                                originX: cw * abscissa,
                                originY: ch * ordinate,
                            }]
                        }
                    };
                },
                data: [0],
            },
        ],
    };
    myChart.setOption(option, true);
    window.addEventListener("resize", () => {
        myChart.resize();
    });
    loopShowTooltip(myChart, option);
    return myChart;
}


/**
 * 左侧
 * 种质来源分布
 */
function zzlyfbChartInit(xAxisData, seriesData, unit = "个") {
    // 背景色列表
    let bacData = seriesData.map(item => 0);
    let myChart = echarts.init(document.getElementById("distribution-germplasm-chart"));
    let option = {
        color: ["#00E4FF"],
        grid: {
            top: 30,
            bottom: 15,
            left: 0,
            right: 10,
            containLabel: true
        },
        tooltip: {
            axisPointer: {
                opacity: 0.2
            },
            ...tooltipUniversal(unit),
            axisPointer: {
                type: "none"
            }
        },
        xAxis: {
            ...xAxisUniversal,
            data: xAxisData
        },
        yAxis: {
            ...yAxisUniversal,
            min: 0,
            name: unit,
            minInterval: 1,
            nameTextStyle: {
                color: "rgba(223, 238, 243, 0.7)",
                fontFamily: "SourceHanSansCNRegular",
                align: "left",
                verticalAlign: "middle"
            }
        },
        series: [
            {
                name: "背景",
                data: bacData,
                type: 'bar',
                barWidth: '60%',
                barGap: '-70%',
                showBackground: true,
                backgroundStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0,
                        1,
                        0,
                        0,
                        [
                            {
                                offset: 0,
                                color: "rgba(255, 255, 255, 0)",
                            },
                            {
                                offset: 1,
                                color: "rgba(255, 255,255, 0.1)",
                            },
                        ],
                        false
                    ),
                },
                zlevel: 9
            },
            {
                name: "品种数量",
                data: seriesData,
                type: 'bar',
                barWidth: '25%',
                itemStyle: {
                    normal: {
                        borderRadius: [15, 15, 0, 0],
                        color: new echarts.graphic.LinearGradient(
                            0,
                            1,
                            0,
                            0,
                            [
                                {
                                    offset: 0,
                                    color: "rgba(3, 232, 234, 0)",
                                },
                                {
                                    offset: 1,
                                    color: "rgba(3, 232, 234, 1)",
                                },
                            ],
                            false
                        ),
                    },
                },
                zlevel: 11
            },
        ]
    };
    myChart.setOption(option, true);
    window.addEventListener("resize", () => {
        myChart.resize();
    });
    loopShowTooltip(myChart, option);
    return myChart;
}


/**
 * 右侧品种采集统计
 */
function pzcjtjChartInit(xAxisData, seriesData, unit = "个") {
    let myChart = echarts.init(document.getElementById("variety-collection-chart"));
    let option = {
        color: ["#00E4FF"],
        grid: {
            top: 30,
            bottom: 25,
            left: 0,
            right: 10,
            containLabel: true
        },
        tooltip: {
            ...tooltipUniversal(unit)
        },
        xAxis: {
            ...xAxisUniversal,
            data: xAxisData
        },
        yAxis: {
            ...yAxisUniversal,
            min: 0,
            name: unit,
            minInterval: 1,
            nameTextStyle: {
                color: "rgba(223, 238, 243, 0.7)",
                fontFamily: "SourceHanSansCNRegular",
                align: "left",
                verticalAlign: "middle"
            }
        },
        series: [
            {
                name: "新增品种数量",
                data: seriesData,
                type: 'line',
                smooth: true,
                symbolSize: 7,
                areaStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(
                            0,
                            1,
                            0,
                            0,
                            [
                                {
                                    offset: 0,
                                    color: "rgba(3, 232, 234, 0)",
                                },
                                {
                                    offset: 1,
                                    color: "rgba(3, 232, 234, 0.5)",
                                },
                            ],
                            false
                        ),
                    },
                },
            }
        ]
    };
    myChart.setOption(option, true);
    window.addEventListener("resize", () => {
        myChart.resize();
    });
    loopShowTooltip(myChart, option);
    return myChart;
}



function loopShowTooltip(chart, chartOption, options) {
    let defaultOptions = {
        interval: 2000,
        loopSeries: false,
        seriesIndex: 0,
        updateData: null
    };

    if (!chart || !chartOption) {
        return;
    }

    let dataIndex = 0; // 数据索引，初始化为-1，是为了判断是否是第一次执行
    let seriesIndex = 0; // 系列索引
    let timeTicket = 0;
    let seriesLen = chartOption.series.length; // 系列个数
    let dataLen = 0; // 某个系列数据个数
    let chartType; // 系列类型
    let first = true;
    let lastShowSeriesIndex = 0;
    let lastShowDataIndex = 0;
    if (seriesLen === 0) {
        return;
    }

    //待处理列表
    //不循环series时seriesIndex指定显示tooltip的系列，不指定默认为0，指定多个则默认为第一个
    //循环series时seriesIndex指定循环的series，不指定则从0开始循环所有series，指定单个则相当于不循环，指定多个
    //要不要添加开始series索引和开始的data索引？

    if (options) {
        options.interval = options.interval || defaultOptions.interval;
        options.loopSeries = options.loopSeries || defaultOptions.loopSeries;
        options.seriesIndex = options.seriesIndex || defaultOptions.seriesIndex;
        options.updateData = options.updateData || defaultOptions.updateData;
    } else {
        options = defaultOptions;
    }

    //如果设置的seriesIndex无效，则默认为0
    if (options.seriesIndex < 0 || options.seriesIndex >= seriesLen) {
        seriesIndex = 0;
    } else {
        seriesIndex = options.seriesIndex;
    }

    /**
     * 清除定时器
     */
    function clearLoop() {
        if (timeTicket) {
            clearInterval(timeTicket);
            timeTicket = 0;
        }
        chart.off('mousemove', stopAutoShow);
        zRender.off('mousemove', zRenderMouseMove);
        zRender.off('globalout', zRenderGlobalOut);
    }

    /**
     * 取消高亮
     */
    function cancelHighlight() {
        /**
         * 如果dataIndex为0表示上次系列完成显示，如果是循环系列，且系列索引为0则上次是seriesLen-1，否则为seriesIndex-1；
         * 如果不是循环系列，则就是当前系列；
         * 如果dataIndex>0则就是当前系列。
         */
        let tempSeriesIndex = dataIndex === 0 ?
            (options.loopSeries ?
                (seriesIndex === 0 ? seriesLen - 1 : seriesIndex - 1)
                : seriesIndex)
            : seriesIndex;
        let tempType = chartOption.series[tempSeriesIndex].type;

        if (tempType === 'pie' || tempType === 'radar') {
            chart.dispatchAction({
                type: 'downplay',
                seriesIndex: lastShowSeriesIndex,
                dataIndex: lastShowDataIndex
            });//wait 系列序号为0且循环系列，则要判断上次的系列类型是否是pie、radar
        }
    }

    /**
     * 自动轮播tooltip
     */
    function autoShowTip() {
        let invalidSeries = 0;
        let invalidData = 0;

        function showTip() {
            //判断是否更新数据
            if (dataIndex === 0 && !first && typeof options.updateData === "function") {
                options.updateData();
                chart.setOption(chartOption);
            }

            let series = chartOption.series;
            let currSeries = series[seriesIndex];
            if (!series || series.length === 0 ||
                !currSeries || !currSeries.type || !currSeries.data ||
                !currSeries.data.length) {
                return;
            }
            chartType = currSeries.type; // 系列类型
            dataLen = currSeries.data.length; // 某个系列的数据个数

            let tipParams = { seriesIndex: seriesIndex };
            switch (chartType) {
                case 'pie':
                case 'map':
                case 'chord':
                    tipParams.name = currSeries.data[dataIndex].name;
                    break;
                case 'radar': // 雷达图
                    tipParams.seriesIndex = seriesIndex;
                    tipParams.dataIndex = dataIndex;
                    break;
                default:
                    tipParams.dataIndex = dataIndex;
                    break;
            }

            if (chartType === 'pie' || chartType === 'radar') {
                if (!first) {
                    cancelHighlight();
                }

                // 高亮当前图形
                chart.dispatchAction({
                    type: 'highlight',
                    seriesIndex: seriesIndex,
                    dataIndex: dataIndex
                });
            }

            // 显示 tooltip
            tipParams.type = 'showTip';

            // 防止updateData时先处理tooltip后刷新数据导出tooltip显示不正确
            setTimeout(() => {
                chart.dispatchAction(tipParams);
            }, 0);

            lastShowSeriesIndex = seriesIndex;
            lastShowDataIndex = dataIndex;
            dataIndex = (dataIndex + 1) % dataLen;
            if (options.loopSeries && dataIndex === 0) { // 数据索引归0表示当前系列数据已经循环完
                invalidData = 0;
                seriesIndex = (seriesIndex + 1) % seriesLen;
                if (seriesIndex === options.seriesIndex) {
                    invalidSeries = 0;
                }
            }

            first = false;
        }

        showTip();
        timeTicket = setInterval(showTip, options.interval);
    }

    // 关闭轮播
    function stopAutoShow() {
        if (timeTicket) {
            clearInterval(timeTicket);
            timeTicket = 0;

            if (chartType === 'pie' || chartType === 'radar') {
                cancelHighlight();
            }
        }
    }

    let zRender = chart.getZr();

    function zRenderMouseMove(param) {
        if (param.event) {
            //阻止canvas上的鼠标移动事件冒泡
            param.event.cancelBubble = true;
        }

        stopAutoShow();
    }

    // 离开echarts图时恢复自动轮播
    function zRenderGlobalOut() {
        if (!timeTicket) {
            autoShowTip();
        }
    }

    // 鼠标在echarts图上时停止轮播
    chart.on('mousemove', stopAutoShow);
    zRender.on('mousemove', zRenderMouseMove);
    zRender.on('globalout', zRenderGlobalOut);

    autoShowTip();

    return {
        clearLoop: clearLoop
    };
}


/**
 * 中国地图初始化
 * @param {*} echarts 实例
 * @param {Array} data 面积渲染数据
 */
function chinaMapCharts(data = [], arr) {
    let mapPointData = { value: [119.5313, 29.8773] }, toCoord = [119.5313, 29.8773];
    myCharts = echarts.init(document.getElementById("container-map"))
    echarts.registerMap('china', chinaJsonT);
    let option = {
        tooltip: {
            show: false,
            trigger: "item",
            backgroundColor: "rgba(17, 53, 58, 0.8)",
            borderColor: "rgba(42,176,154,1)",
            borderWidth: 2,
            textStyle: {
                color: "rgba(37, 255, 212, 0.9)"
            },
            formatter: function (params) {
                if (params.data && params.data.name) {
                    let html = `${params.data && params.data.name}<br>销售量：${params.data && params.data.sale_volume}<br>销售额：${params.data && params.data.sale_money}`
                    return html
                } else {
                    return
                }

            }
        },
        geo: [{
            map: "china",
            type: "map",
            roam: false,
            zoom: 0.8,
            itemStyle: {
                areaColor: 'rgba(59,103,130, 0.7)',
                borderColor: "rgba(255,255,255,0)",
                shadowColor: "rgba(59,103,130,1)",
                shadowOffsetX: -5,
                shadowOffsetY: 7
            },
            regions: [{
                name: '南海诸岛',
                itemStyle: {
                    areaColor: "rgba(61, 255, 229,1)",
                    normal: {
                        opacity: 0,
                        label: {
                            show: false,
                            color: "#009cc9"
                        }
                    }
                },
            }],
        },
        ],
        series: [{
            name: "省会",
            type: "map",
            map: 'china',
            zoom: 0.8,
            // geoIndex: 0,
            roam: false,
            itemStyle: {
                areaColor: {
                    type: 'linear-gradient',
                    x: 200,
                    y: 500,
                    x2: 700,
                    y2: 500,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(33, 74, 180, 0.2)', // 0% 处的颜色
                    }, {
                        offset: 0.5,
                        color: 'rgba(33, 74, 180, 0.2)' // 0% 处的颜色
                    }, {
                        offset: 1,
                        color: 'rgba(33, 74, 180, 0.4)' // 100% 处的颜色
                    }],
                    global: true // 缺省为 false
                },
                borderColor: "#fff",
                borderWidth: 2
            },
            emphasis: {
                itemStyle: {
                    areaColor: "rgba(33, 74, 180, 0.1)",
                    borderColor: "rgba(235, 235, 44, 1)",
                    borderWidth: 2
                },
                label: {
                    show: true
                }
            },
            select: {
                itemStyle: {
                    color: null, //设置地图点击后的颜色
                },
                label: {
                    show: true,
                    color: "rgba(236,233,235,1)"
                }
            },
            label: {
                show: true,
                color: "rgba(236,233,235,1)"
            },
            data: arr
        },
        {
            type: "lines",
            zlevel: 2,
            effect: {
                color: "#16EF44",
                show: true,
                period: 4, //箭头指向速度，值越小速度越快
                trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
                symbol: "arrow", //箭头图标
                symbolSize: 5, //图标大小
            },
            lineStyle: {
                normal: {
                    color: "#DBA417",
                    shadowColor: "rgba(222,179,70,0.3)",
                    shadowBlur: 1,
                    width: 2, //尾迹线条宽度
                    opacity: 1, //尾迹线条透明度
                    curveness: 0.3, //尾迹线条曲直度
                },
            },
            data: data,
        }, {
            type: "scatter",
            coordinateSystem: "geo",
            showEffectOn: "render",
            zlevel: 1,
            rippleEffect: {
                period: 15,
                scale: 4,
                brushType: "fill",
            },
            hoverAnimation: true,
            label: {
                normal: {
                    formatter: "{b}",
                    position: "right",
                    offset: [15, 0],
                    color: "#1DE9B6",
                    show: true,
                },
            },
            itemStyle: {
                normal: {
                    color: "#16EF44"
                }
            },
            symbolSize: 10,
            data: mapPointData,
        }, {
            type: "effectScatter",
            coordinateSystem: "geo",
            showEffectOn: "render",
            zlevel: 1,
            rippleEffect: {
                period: 15,
                scale: 4,
                brushType: "fill",
            },
            hoverAnimation: true,
            label: {
                normal: {
                    formatter: "{b}",
                    position: "right",
                    offset: [15, 0],
                    color: "#1DE9B6",
                    show: true,
                },
            },
            itemStyle: {
                normal: {
                    color: "#fff"
                }
            },
            symbolSize: 7,
            data: [{ value: toCoord }],
        }]
    }
    myCharts.setOption(option, true)
    window.addEventListener("resize", () => {
        myCharts.resize()
    })
    myCharts.on('georoam', function (params) {
        var option = myCharts.getOption();//获得option对象
        if (params.zoom != null && params.zoom != undefined) { //捕捉到缩放时
            option.geo[0].zoom = option.series[0].zoom;//下层geo的缩放等级跟着上层的geo一起改变
            option.geo[0].center = option.series[0].center;//下层的geo的中心位置随着上层geo一起改变
            // option.geo[1].zoom = option.series[0].zoom;// 第三层改变
            // option.geo[1].center = option.series[0].center;//第三层改变
        } else {//捕捉到拖曳时
            option.geo[0].center = option.series[0].center;//下层的geo的中心位置随着上层geo一起改变
            // option.geo[1].center = option.series[0].center;// 第三层改变
        }
        myCharts.setOption(option);//设置option
    });
};

/**
 * 初始化世界地图图表
 * @param {*} echarts 实例
 * @param {*} data    面积渲染数据 
 */
function worldMapCharts(data = []) {
    let myCharts = echarts.init(document.getElementById("container-map-world"));
    echarts.registerMap('world', worldJsonT);
    let linesData = [];
    if (data.length) {
        linesData = [
        ];
        data.forEach(item => {
            let obj = worldJsonT.features.find(el => {
                return el.properties.name == item.name;
            });
            if (obj && obj.geometry && obj.geometry.coordinates) {
                linesData.push([
                        {
                            coord: obj.geometry.coordinates[0][0][0][0] ? obj.geometry.coordinates[0][0][0] : obj.geometry.coordinates[0][0],
                            value: item.number
                        },
                        {
                            coord: [87.617729, 43.792816],
                        }
                    ]
                )
            }
        });
    }
    
    let option = {
        tooltip: {
            show: false,
            trigger: "item",
            backgroundColor: "rgba(17, 53, 58, 0.8)",
            borderColor: "rgba(58,130,162,1)",
            borderWidth: 2,
            textStyle: {
                color: "rgba(249, 185, 54, 1)"
            },
        },
        geo: {
            map: "world",
            type: "map",
            roam: false,
            zoom: 0.7,
            itemStyle: {
                areaColor: "rgba(74,225,208,1)",
                borderColor: "rgba(16,133,63,1)",
                shadowColor: "rgba(126,225,246,1)",
                shadowOffsetX: 3,
                shadowOffsetY: 7
            }
        },
        series: [{
            type: "map",
            map: 'world',
            zoom: 0.7,
            itemStyle: {
                areaColor: {
                    type: 'linear-gradient',
                    x: 200,
                    y: 500,
                    x2: 800,
                    y2: 300,
                    colorStops: [{
                        offset: 0,
                        color: 'rgba(80,201,158,1)' // 0% 处的颜色
                    },{
                        offset: 0.1,
                        color: 'rgba(0,124,156,1)', // 0% 处的颜色
                    },{
                        offset: 0.5,
                        color: 'rgba(80,201,158,1)' // 0% 处的颜色
                    }, {
                        offset: 0.7,
                        color: 'rgba(0,124,156,1)' // 100% 处的颜色
                    },{
                        offset: 1,
                        color: 'rgba(80,201,158,1)' // 100% 处的颜色
                    }],
                    global: true // 缺省为 false
                }
            },
            label: {
                color: "rgba(236,233,235,1)",
                formatter: (param) => {
                    if (param.name) {
                        return worldAreaNameMap[param.name]
                    }
                }
            },
            emphasis: {
                // disabled: true,
                itemStyle: {
                    areaColor: "rgba(146, 152, 35, 0.54)",
                    borderColor: "rgba(235, 235, 44, 1)",
                    borderWidth: 2
                },
                label: {
                    show: true,
                    color: "rgba(235, 235, 44, 0.8)"
                }
            },
            select: {
                disabled: false,
                itemStyle: {
                    color: null, //设置地图点击后的颜色
                },
                label: {
                    show: false,
                    color: "rgba(236,233,235,1)"
                }
            },
            silent: true,
            data: [
                {
                    name: "中国",
                    selected: true,
                    select: {
                        itemStyle: {
                            areaColor: "rgba(146, 152, 35, 0.54)",
                            borderColor: "rgba(235, 235, 44, 1)",
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            color: "rgba(236,233,235,1)"
                        }
                    },
                    // itemStyle: {
                    //     borderColor: "#fff",
                    //     borderWidth: 2,
                    //     opacity: 1,
                    //     shadowColor: '#fff',
                    //     shadowBlur: 3
                    // }
                }
            ]
        },
        //地图线的动画效果
        {
            type: 'lines',
            zlevel: 2,
            effect: {
                color: '#16EF44',
                show: true,
                period: 4, //箭头指向速度，值越小速度越快
                trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
                symbol: 'arrow', //箭头图标
                symbolSize: 7, //图标大小
            },
            lineStyle: {
                normal: {
                    color: '#16EF44',
                    shadowColor: 'rgba(61,236,79,0.3)',
                    shadowBlur: 5,
                    width: 2, //尾迹线条宽度
                    opacity: 1, //尾迹线条透明度
                    curveness: 0.3, //尾迹线条曲直度
                },
            },
            data: linesData,
        },]
    }
    myCharts.setOption(option, true)
    window.addEventListener("resize", () => {
        myCharts.resize()
    });
    myCharts.on('click', function (params) {
        if (params.name == "中国") {
            myCharts.dispose();
            setTimeout(() => {
                vm.showChinaMap = true;
                vm.mapType = 2;
            }, 300);
        }
    })
}
